﻿/*
*  ChgDoc CMS - GNU General Public License, version 3 (GPL-3.0)
*  Copyright (C)  2012. Ian Quigley
*  
*  This program is free software: you can redistribute it and/or modify
*  it under the terms of the GNU General Public License as published by
*  the Free Software Foundation, either version 3 of the License, or
*  (at your option) any later version.
*  
*  This program is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU General Public License for more details.
*/


pickFile = function (selector) {

    selectFileDialog({
        selected: function (file) { $(selector).val(file); $(selector).trigger('keyup'); }
    });
}

myValueHookLoad = function ( fnDefault, tag, attr, value) { 
    
    if (attr !== 'style')
        return fnDefault(null, tag, attr, value);

    return cssTool.condense(value);
}

myEditHook = function (fnDefault, tag, attr, value) {

    if (attr !== 'src')
        return fnDefault(null, tag, attr, value);

    return "<input type='text' id='editcms_" + tag + "_" + attr + "' data-attr='" + attr +"' value='" + value + "' style='width:100%'/><a href='#' onclick=\"pickFile('#editcms_" + tag + "_" + attr + "')\">Select</a>";
}

var defaultHooks = {
 
    valueHookLoad : function (fnDefault, tag, attr, value) {
        return value;
    },

    valueHookSave : function (fnDefault, tag, attr, value) {
        return value; 
    },

    editHook : function (fnDefault, tag, attr, value) {
        return "<textarea data-attr='" + attr + "' style='width:100%; height:100%;'>" + value + "</textarea>"; 
    }
}

editHtmlElement = function (options) {

    if (typeof (jQuery) === undefined)
        alert('Missing jQuery');

    if (typeof (jQuery.ui) === undefined)
        alert('Missing jQuery.ui');

    var internal = {
        element: '',
        valueHookLoad: defaultHooks.valueHookLoad,
        valueHookSave: defaultHooks.valueHookSave,
        editHook: defaultHooks.editHook,

        ok: function (element) { }
    };

    for (var member in options)
        internal[member] = options[member];

    if (internal.title === undefined)
        internal.title = "Edit &lt;" + internal.element.tagName + "&gt; tag";

    this.show = function () {

        $('#editHtmlElement').remove();	
		$('body').append("<div id='editHtmlElement'></div>");
		$('#editHtmlElement').append(createHtml());
		$("#tabs").tabs();
		

        $('#editHtmlElement').dialog({
            title: internal.title,
            width: 600,
            height: 400,
            modal: true,
            position: 'center',
            resize: onDialogResize,
            buttons: {
				"Parent" : function () {	
					internal.element = internal.element.parentNode;
					rebuildHtml();
					$(this).dialog('options','title', "Edit &lt;" + internal.element.tagName + "&gt; tag");
					onDialogResize();
					disableSave();
					$('#tabs *[data-attr]').bind('keyup', enableSave);
					},
				"Apply": function () {
					saveElement(),
					internal.ok(internal.element);
				},				
                "Save": function () {
                    saveElement(),
					internal.ok(internal.element);
                    $(this).dialog("close");
                },
                "Cancel": function () {
                    $(this).dialog("close");
                }
            }
        });

        onDialogResize();
        disableSave();
        $('#tabs *[data-attr]').bind('keyup', enableSave);
        $('#tabs *[data-item]').bind('keyup', enableSave);
    }

    onDialogResize = function (event, ui) {

        var availHeight = $('div#tabs').height() - $("div[id^=tab-]").position().top - 30;

        $("div[id^=tab-]").css('height', availHeight);
    }
	
	// ====================================
	rebuildHtml = function () {
		
		$('#editHtmlElement').empty();
		$('#editHtmlElement').append(createHtml());
		$("#tabs").tabs();
	}
	
	createHtml = function () {
	
		var hasInnerHtml = internal.element.hasChildNodes();
        var htmlName = "Html";
        if (internal.element.tagName === 'P')
            htmlName = "Text";


        var html = "<div id='tabs' style='height:100%;'><ul>";
        if (hasInnerHtml)
            html += "<li><a href='#tab-html'>" + htmlName + "</a></li>";

        for (var i = 0; i < internal.element.attributes.length; i++) {
            html += "<li><a href='#tab-" + i + "'>" + internal.element.attributes[i].name + "</a></li>";
        }

        html += "<li><a href='#tab-add'>New</a></li>";

        html += "</ul>";

        if (hasInnerHtml)
            html += "<div id='tab-html'><textarea data-item='html' style='width:98%; height:98%;'>" + internal.element.innerHTML + "</textarea></div>";

        for (var i = 0; i < internal.element.attributes.length; i++) {
            var name = internal.element.attributes[i].name;
            var value = internal.element.attributes[i].value;
            var tagName = internal.element.tagName;

            value = internal.valueHookLoad(defaultHooks.valueHookLoad, tagName, name.toLowerCase(), value)

            html += "<div id='tab-" + i + "'>" + internal.editHook(defaultHooks.editHook, tagName, name.toLowerCase(), value) + "</div>";
        }
        html += "<div id='tab-add' style='padding: 10px;' >Name: <input type=text id='addTabName' /> <input type=button value='add' onclick='addTag()'/></div>";
        html += "</div>";

        return html;
	}

    addTag = function () {

        var name = $('#addTabName').val();
        if (name.length === 0 || name === 'html')
            return;

        var count = $('#tabs ul li').length;

        $("#tabs").tabs('add', '#tab-' + count, name, count - 1);

        $("#tabs ul").after("<div id='tab-" + count + "' class='ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide'><textarea data-attr='" + name + "'>aa</textarea></div>");

        enableSave();
    }

    // ========================================
    saveElement = function () {

        var elem = $(internal.element);
        $('#editHtmlElement *[data-attr]').each(function (i, item) {
            var jqi = $(item);
            elem.attr(jqi.attr('data-attr'), jqi.val());
        });

        if ($('#editHtmlElement textarea[data-item=html]').length !== 0) {
            elem.html($('#editHtmlElement textarea[data-item=html]').val());
        }
    }

    enableSave = function (text) {
        $('.ui-dialog-buttonset :button:contains(Save)').removeAttr("disabled").removeClass("ui-state-disabled");
        $('#tabs *[data-attr]').unbind('keyup', enableSave);
        $('#tabs *[data-item]').unbind('keyup', enableSave);
    };

    disableSave = function () {
        $('.ui-dialog-buttonset :button:contains(Save)').attr("disabled", "disabled").addClass("ui-state-disabled");
    };
};